package com.hzgj.tool;

import com.hzgj.bcl.util.lang.StrKit;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class Exec {

    private static Logger logger = LoggerFactory.getLogger(Exec.class);

    public static void run(SSHClient ssh, String command) throws Exception {
        final Session session = ssh.startSession();
        try {
            final Command cmd = session.exec(command);
            String message = IOUtils.readFully(cmd.getErrorStream()).toString();
            if (StrKit.notBlank(message)) {
                logger.info(message);
            } else {
                logger.info(ssh.getRemoteAddress() + ":" + IOUtils.readFully(cmd.getInputStream()).toString());
            }
            cmd.join(5, TimeUnit.SECONDS);
        } finally {
            session.close();
        }
    }
}